/* 
Name: getport.cpp
Date: 2009/7/28
Creator: Dory Wang
Contributor: Dory Wang, Vicent Wang
Compiler: Microsoft Visual Studio 2005
Function: Strcmp()
WIN_32_API: RegOpenKeyE(), RegQueryKeyEx(), RegCloseKey()
ASCII version
*/
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <string>

using namespace std;

/*void Search_Port_Number(LPBYTE Port_Name)
{
	
}
*/

LPBYTE GetPort()
{
    
	//Open Rigster Path
	HKEY hkey;
	LPCTSTR lpsubkey = _T("SYSTEM\\CurrentControlSet\\Services\\Ser2pl\\Enum\\");
	long usb = RegOpenKeyEx(HKEY_LOCAL_MACHINE,lpsubkey,0,KEY_READ,&hkey);
	
	//Check USB Device of "0"
	LPBYTE Device_Info;
	Device_Info = new BYTE[100];
	DWORD buffersize = 100;
	ULONG bfrtype = REG_SZ;
	
	LPBYTE Port_Name = new BYTE[10];
	LPBYTE All_Port = new BYTE[4];

	if(usb!=ERROR_SUCCESS) false;
	else if(RegQueryValueEx(hkey,_T("0"),0,&bfrtype,Device_Info,&buffersize)!=ERROR_SUCCESS)
		false;
	else
	{
		//Compare the USB Device to see if there are my Device.
		char My_Device[] = {"USB\\VID_067B&PID_2303"}; //22 characters

		//Use Strncmp() to compare the My_Device and Device_Info
		char* DeInfo = (char *)Device_Info;
		char* MyDev = My_Device;
		int My_Device_String_Length = (sizeof(My_Device))/sizeof(My_Device[0])-1; 
			
		if(strncmp(DeInfo,MyDev,My_Device_String_Length)!=ERROR_SUCCESS) cout <<"Not My Device"<<endl;
		else
		{
			cout <<"My Device Found"<<endl;
			
			LPCTSTR lp_enum = _T("SYSTEM\\CurrentControlSet\\Enum\\");
			LPCTSTR Device_Path = (LPCTSTR)Device_Info;
			
			long Temp_1 = RegOpenKeyEx(HKEY_LOCAL_MACHINE,lp_enum,0,KEY_READ,&hkey);
			long Temp_2 = RegOpenKeyEx(hkey,Device_Path,0,KEY_READ,&hkey);
			long Temp_3 = RegOpenKeyEx(hkey,_T("Device Parameters\\"),0,KEY_READ,&hkey);
			
			if( Temp_1 && Temp_2 && Temp_3!=ERROR_SUCCESS)
				false;					
			else if (RegQueryValueEx(hkey,_T("PortName"),0,&bfrtype,Port_Name,&buffersize)!=ERROR_SUCCESS)
				false;
		}
	}

	RegCloseKey(hkey);
	return Port_Name;
}
 int main()
 {
	
	
	cout<<GetPort()<<endl;

	system("pause");
    return 0;
 
 }
